package com.redwood.report.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.redwood.report.ItemDecoration.SpaceItemDecoration;
import com.redwood.report.R;
import com.redwood.report.activity.bak.BaoXiuDetailActivity;
import com.redwood.report.adapter.bak.WeiChuLiAdapter;
import com.redwood.report.common.Config;
import com.redwood.report.common.Constant;
import com.redwood.report.database.DataBaseHelper;
import com.redwood.report.entity.bak.BaoXiuInfo;
import com.redwood.report.entity.ServiceResult;
import com.redwood.report.entity.bak.been.BaoXiuSearchBeen;
import com.redwood.report.entity.bak.been.ListBaoXiuBeen;
import com.redwood.report.entity.bak.been.ListWeiXiuBeen;
import com.redwood.report.event.QRChangeEvent;
import com.redwood.report.event.RedChangeEvent;
import com.redwood.report.event.ShuaXinEvent;
import com.redwood.report.net.Api;
import com.redwood.report.net.NetUtils;
import com.redwood.report.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 未处理 处理中 已完成
 */
public class WeiChuliFragment extends BaseLazyFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.rb_yuwoxiangguan)
    CheckBox rbYuwoxiangguan;
    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.search_iv)
    ImageView searchIv;
    @BindView(R.id.saomao_iv)
    ImageView saomaoIv;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.count_tv)
    TextView countTv;
    private String doingType;
    private String renyuanType;
    private static final String DOING_TYPE = "DOING_TYPE";
    private static final String REYUAN_TYPE = "REYUAN_TYPE";
    private int page = 1;
    private int totalpage = Integer.MAX_VALUE;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    private BaseQuickAdapter homeAdapter;
    private boolean aboutMe=false;
    /**
     * 布局文件ID（重载）
     *
     * @return
     */
    protected int getLayoutId() {
        return R.layout.fragment_weichuli;
    }

    /***
     *
     * @param doingType 工单当前状态 未处理 处理中 已处理
     * @param renyuanType 管理员 维修人 报修人
     * @return
     */
    public static WeiChuliFragment newInstance(String doingType, String renyuanType) {
        WeiChuliFragment fragment = new WeiChuliFragment();
        Bundle args = new Bundle();
        args.putString(DOING_TYPE, doingType);
        args.putString(REYUAN_TYPE, renyuanType);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQRChangeEven(QRChangeEvent event) {
        searchEt.setText( event.qr);
        onRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShuaXinEvent(ShuaXinEvent event) {
        if(event.dqtype.equals(doingType)) {
            onRefresh();
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void managerArguments() {
        doingType = getArguments().getString(DOING_TYPE);
        renyuanType = getArguments().getString(REYUAN_TYPE);
    }

    /**
     * 初始化组件（重载）
     */
    protected void initViewData(View entryView) {
        initAdapter();
        if (doingType.equals(Constant.WEICHULI)) {
            //tvName.setText("未处理");
            //为了一加载就显示红点 放弃了懒加载
            loadChuliZhongByServer(false);
            searchLl.setVisibility(View.GONE);
        } else if (doingType.equals(Constant.ChuLIZHONG)) {
            //tvName.setText("处理中");
            //loadChuliZhongByServer(false);
            loadChuliZhongByServer(false);
            searchLl.setVisibility(View.GONE);
        } else if (doingType.equals(Constant.YICHULI)) {
            //tvName.setText("已处理");
            searchLl.setVisibility(View.VISIBLE);

        }
        if(renyuanType.equals(Constant.BAOXIUREN)){
            rbYuwoxiangguan.setVisibility(View.GONE);
            aboutMe=false;
        }

        searchIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        saomaoIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //startActivity(new Intent(getActivity(),CameraCaptureActivity.class));
            }
        });
        rbYuwoxiangguan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                aboutMe=isChecked;
                onRefresh();
            }
        });
    }
    private void initAdapter() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.addItemDecoration(new SpaceItemDecoration(getActivity()).setSpace(3f).setSpaceColor(getResources().getColor(R.color.item_press2)));
        homeAdapter = new WeiChuLiAdapter(null, doingType);
        homeAdapter.setOnLoadMoreListener(this, rvList);
        homeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {

                }
            }
        });
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                Intent intent=new Intent(getActivity(), BaoXiuDetailActivity.class);
                String wxid="";
                MultiItemEntity multiItemEntity= (MultiItemEntity) adapter.getData().get(position);
                boolean hasred=true;
                if( multiItemEntity instanceof ListBaoXiuBeen){
                    wxid=((ListBaoXiuBeen)multiItemEntity).getBaoXiuSearchBeen().getWxid();
                    hasred=((ListBaoXiuBeen)multiItemEntity).getBaoXiuSearchBeen().isHasRed();
                }
                if(adapter.getData().get(position) instanceof ListWeiXiuBeen){
                    wxid=((ListWeiXiuBeen)multiItemEntity).getBaoXiuSearchBeen().getWxid();
                    hasred=((ListWeiXiuBeen)multiItemEntity).getBaoXiuSearchBeen().isHasRed();
                }
                if(doingType.equals(Constant.WEICHULI)&&hasred) {
                    DataBaseHelper.getInstance().insert(true, Config.getUserInfo().getUserid(), wxid);
                }
                if(doingType.equals(Constant.ChuLIZHONG)&&hasred) {
                    DataBaseHelper.getInstance().insert(false, Config.getUserInfo().getUserid(), wxid);
                }
                intent.putExtra("wxid",wxid);
                intent.putExtra(Constant.DOING_TYPE,doingType);
                startActivity(intent);
            }
        });
        rvList.setAdapter(homeAdapter);
    }

    @Override
    public void onRefresh() {
        page = 1;
        totalpage = Integer.MAX_VALUE;
        loadChuliZhongByServer(false);
    }

    private void loadChuliZhongByServer(final boolean isLoadMore) {
      /*  if (renyuanType.equals(Constant.BAOXIUREN)) {
            totalpage = 30/10;
            List<ListBaoXiuBeen> listBaoXiuBeens = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                ListBaoXiuBeen listBaoXiuBeen = new ListBaoXiuBeen();
                listBaoXiuBeens.add(listBaoXiuBeen);
            }
            if (page == 1) {
                homeAdapter.setNewData(listBaoXiuBeens);
            } else {
                homeAdapter.addData(listBaoXiuBeens);
            }
            page++;
            if (isLoadMore) {
                refreshLayout.setEnabled(true);
                homeAdapter.loadMoreComplete();
            } else {
                refreshLayout.setRefreshing(false);
            }
        } else if (renyuanType.equals(Constant.WEIXIUREN)) {
            totalpage = 10/10;
            List<ListWeiXiuBeen> listBaoXiuBeensw = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                ListWeiXiuBeen listBaoXiuBeenw = new ListWeiXiuBeen();
                listBaoXiuBeensw.add(listBaoXiuBeenw);
            }
            homeAdapter.setNewData(listBaoXiuBeensw);
            page++;
            if (isLoadMore) {
                refreshLayout.setEnabled(true);
                homeAdapter.loadMoreComplete();
            } else {
                refreshLayout.setRefreshing(false);
            }
        } else if (renyuanType.equals(Constant.GUANLIYUAN)) {
            totalpage = 10/10;
            List<ListWeiXiuBeen> listBaoXiuBeensw = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                ListWeiXiuBeen listBaoXiuBeenw = new ListWeiXiuBeen();
                listBaoXiuBeensw.add(listBaoXiuBeenw);
            }
            homeAdapter.setNewData(listBaoXiuBeensw);
            page++;
            if (isLoadMore) {
                refreshLayout.setEnabled(true);
                homeAdapter.loadMoreComplete();
            } else {
                refreshLayout.setRefreshing(false);
            }
        }

        if (doingType.equals(Constant.WEICHULI)) {

            //loadWeiChuliByServer(true);
        } else if (doingType.equals(Constant.ChuLIZHONG)) {
            //loadChuliZhongByServer(true);
        } else if (doingType.equals(Constant.YICHULI)) {

        }
        countTv.setText("共计"+homeAdapter.getData().size()+"条");*/

        if(rbYuwoxiangguan.getVisibility()==View.VISIBLE) {
            aboutMe=rbYuwoxiangguan.isChecked();
        }
        if(renyuanType.equals(Constant.BAOXIUREN)){
            aboutMe=false;
        }
        if (doingType.equals(Constant.YICHULI)) {
            String searchKey=searchEt.getText().toString();
            Api.getListByKey(getActivity(),aboutMe,searchKey, page , Constant.PAGE_SIZE, new NetUtils.NetCallBack<ServiceResult>() {
                @Override
                public void success(ServiceResult rspData) {
                    refreshLayout.setRefreshing(false);
                    BaoXiuInfo info = (BaoXiuInfo) rspData;
                    if (rspData.getRecode() == 1) {
                        if (info.getData() != null && info.getData().size() > 0) {
                            if (renyuanType.equals(Constant.BAOXIUREN)) {
                                List<ListBaoXiuBeen> listBaoXiuBeens = new ArrayList<>();

                                for (BaoXiuSearchBeen searchBeen : info.getData()) {
                                    ListBaoXiuBeen baoXiuBeen = new ListBaoXiuBeen();
                                    baoXiuBeen.setBaoXiuSearchBeen(searchBeen);
                                    listBaoXiuBeens.add(baoXiuBeen);
                                }
                                if (page == 1) {
                                    homeAdapter.setNewData(listBaoXiuBeens);
                                } else {
                                    homeAdapter.addData(listBaoXiuBeens);
                                }
                            } else if (renyuanType.equals(Constant.WEIXIUREN) || renyuanType.equals(Constant.GUANLIYUAN)) {
                                List<ListWeiXiuBeen> listBaoXiuBeens = new ArrayList<>();
                                for (BaoXiuSearchBeen searchBeen : info.getData()) {
                                    ListWeiXiuBeen baoXiuBeen = new ListWeiXiuBeen();
                                    baoXiuBeen.setBaoXiuSearchBeen(searchBeen);
                                    listBaoXiuBeens.add(baoXiuBeen);
                                }
                                if (page == 1) {
                                    homeAdapter.setNewData(listBaoXiuBeens);
                                } else {
                                    homeAdapter.addData(listBaoXiuBeens);
                                }
                            }
                        } else {
                            if (renyuanType.equals(Constant.BAOXIUREN)) {
                                homeAdapter.setNewData(new ArrayList<ListBaoXiuBeen>());
                            } else {
                                homeAdapter.setNewData(new ArrayList<ListWeiXiuBeen>());
                            }

                        }
                        homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
                        totalpage = (info.getCount() + Constant.PAGE_SIZE - 1) / Constant.PAGE_SIZE;
                        page++;
                        if (isLoadMore) {
                            refreshLayout.setEnabled(true);
                            homeAdapter.loadMoreComplete();
                        } else {
                            refreshLayout.setRefreshing(false);
                        }
                        countTv.setText("共" + info.getCount() + "条");
                    } else {
                        if (isLoadMore) {
                            refreshLayout.setEnabled(true);
                            homeAdapter.loadMoreFail();
                        } else {
                            refreshLayout.setRefreshing(false);
                        }
                        ToastUtils.show(rspData.getMsg());
                    }
                    homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
                }

                @Override
                public void failed(String msg) {
                    if (isLoadMore) {
                        refreshLayout.setEnabled(true);
                        homeAdapter.loadMoreFail();
                    } else {
                        refreshLayout.setRefreshing(false);
                    }
                    ToastUtils.show(msg);
                }

                @Override
                public void onUsedCache(String msg) {

                }
            }, BaoXiuInfo.class);
        }else {

            Api.baoXiuSearch(getActivity(), doingType, aboutMe, page, Constant.PAGE_SIZE, new NetUtils.NetCallBack<ServiceResult>() {
                @Override
                public void success(ServiceResult rspData) {
                    int notRedCount=0;
                    refreshLayout.setRefreshing(false);
                    BaoXiuInfo info = (BaoXiuInfo) rspData;
                    if (rspData.getRecode() == 1) {
                        if (info.getData() != null && info.getData().size() > 0) {
                            if (renyuanType.equals(Constant.BAOXIUREN)) {
                                List<ListBaoXiuBeen> listBaoXiuBeens = new ArrayList<>();
                                List<String> redList=new ArrayList<>();
                                if(doingType.equals(Constant.WEICHULI)) {
                                    redList=DataBaseHelper.getInstance().getAllRedServerid(true, Config.getUserInfo().getUserid());
                                }else{
                                    redList=DataBaseHelper.getInstance().getAllRedServerid(false, Config.getUserInfo().getUserid());
                                }
                                for (BaoXiuSearchBeen searchBeen : info.getData()) {
                                    ListBaoXiuBeen baoXiuBeen = new ListBaoXiuBeen();
                                    baoXiuBeen.setBaoXiuSearchBeen(searchBeen);
                                    if(redList.size()>0){
                                        for(String redstr:redList){
                                            if(redstr.equals(searchBeen.getWxid())||Config.getUserInfo().getUsername().equals(baoXiuBeen.getBaoXiuSearchBeen().getAppName())) {
                                                searchBeen.setHasRed(false);
                                                notRedCount++;
                                                break;
                                            }
                                        }
                                    }
                                    listBaoXiuBeens.add(baoXiuBeen);
                                }
                                if (page == 1) {
                                    homeAdapter.setNewData(listBaoXiuBeens);
                                } else {
                                    homeAdapter.addData(listBaoXiuBeens);
                                }
                            } else if (renyuanType.equals(Constant.WEIXIUREN) || renyuanType.equals(Constant.GUANLIYUAN)) {
                                List<ListWeiXiuBeen> listBaoXiuBeens = new ArrayList<>();
                                List<String> redList=new ArrayList<>();
                                if(doingType.equals(Constant.WEICHULI)) {
                                    redList=DataBaseHelper.getInstance().getAllRedServerid(true, Config.getUserInfo().getUserid());
                                }else{
                                    redList=DataBaseHelper.getInstance().getAllRedServerid(false, Config.getUserInfo().getUserid());
                                }
                                for (BaoXiuSearchBeen searchBeen : info.getData()) {
                                    ListWeiXiuBeen baoXiuBeen = new ListWeiXiuBeen();
                                    baoXiuBeen.setBaoXiuSearchBeen(searchBeen);
                                    if(redList.size()>0){
                                        for(String redstr:redList){
                                            if(redstr.equals(searchBeen.getWxid())||Config.getUserInfo().getUsername().equals(baoXiuBeen.getBaoXiuSearchBeen().getAppName())) {
                                                searchBeen.setHasRed(false);
                                                notRedCount++;
                                                break;
                                            }
                                        }
                                    }
                                    listBaoXiuBeens.add(baoXiuBeen);
                                }
                                if (page == 1) {
                                    homeAdapter.setNewData(listBaoXiuBeens);
                                } else {
                                    homeAdapter.addData(listBaoXiuBeens);
                                }
                            }
                        } else {
                            if (renyuanType.equals(Constant.BAOXIUREN)) {
                                homeAdapter.setNewData(new ArrayList<ListBaoXiuBeen>());
                            } else {
                                homeAdapter.setNewData(new ArrayList<ListWeiXiuBeen>());
                            }

                        }
                        EventBus.getDefault().post(new RedChangeEvent((info.getCount()-notRedCount),doingType));
                        homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
                        totalpage = (info.getCount() + Constant.PAGE_SIZE - 1) / Constant.PAGE_SIZE;
                        page++;
                        if (isLoadMore) {
                            refreshLayout.setEnabled(true);
                            homeAdapter.loadMoreComplete();
                        } else {
                            refreshLayout.setRefreshing(false);
                        }
                        countTv.setText("共" + info.getCount() + "条");
                    } else {
                        if (isLoadMore) {
                            refreshLayout.setEnabled(true);
                            homeAdapter.loadMoreFail();
                        } else {
                            refreshLayout.setRefreshing(false);
                        }
                        ToastUtils.show(rspData.getMsg());
                    }
                    homeAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) rvList.getParent());
                }

                @Override
                public void failed(String msg) {
                    if (isLoadMore) {
                        refreshLayout.setEnabled(true);
                        homeAdapter.loadMoreFail();
                    } else {
                        refreshLayout.setRefreshing(false);
                    }
                    ToastUtils.show(msg);
                }

                @Override
                public void onUsedCache(String msg) {

                }
            }, BaoXiuInfo.class);
        }
    }

    //加载更多
    @Override
    public void onLoadMoreRequested() {
        refreshLayout.setEnabled(false);
        if (page > totalpage) {
            refreshLayout.setEnabled(true);
            homeAdapter.loadMoreEnd(false);
            return;
        } else {
            if (homeAdapter.getData().size() < Constant.PAGE_SIZE) {
                homeAdapter.loadMoreEnd(true);
            } else {
                loadChuliZhongByServer(true);


            }
        }
    }


    /**
     * 初始化数据,必须重载（重载）
     */
    protected void initData() {
        loaded();
    }

    /**
     * 第一次页面呈现的时候调用（重载）
     */
    protected void onFirstUserVisible() {
        //初始化数据
        if (doingType.equals(Constant.YICHULI)) {
            loadChuliZhongByServer(false);
        }
    }

    /**
     * 非第一次页面呈现的时候调用（重载）
     */
    protected void onUserVisible() {

    }

    /**
     * 第一次页面消失的时候调用（重载）
     */
    protected void onFirstUserInvisible() {
    }

    /**
     * 非第一次页面消失的时候调用（重载）
     */
    protected void onUserInvisible() {

    }


}
